import React, { useRef, useState } from 'react';

import { useNavigate } from 'react-router-dom';

import { PlusOutlined, ReloadOutlined, SettingOutlined } from '@ant-design/icons';

import {
  type ProjectInfo,
  type ProjectDetail,
  deviceProjectListApi,
  deviceProjectDeleteApi,
  deviceProjectAddApi,
  deviceProjectDetailApi,
} from '@/api/projectManager';
import type { OperationType } from '@/constants';
import { OperationTypeList } from '@/constants';
import { TableLocalePresets } from '@/utils/tableUtils';

import ProjectAddForm from './modules/add';

import type { ActionType, ProColumns } from '@ant-design/pro-components';

/**
 * 项目管理页面组件
 * 提供项目的创建、编辑、删除等功能
 */
const ProjectManager = () => {
  // 路由导航
  const navigate = useNavigate();

  // 表格操作引用
  const actionRef = useRef<ActionType>(null);

  // 表单实例
  const [form] = AForm.useForm();

  // 抽屉状态管理
  const [drawerShow, setDrawerShow] = useState(false);
  const [drawerType, setDrawerType] = useState<OperationType>('ADD');
  const [currentRecord, setCurrentRecord] = useState<Partial<ProjectInfo>>({});

  /**
   * 获取项目列表数据
   * @param params 查询参数
   * @returns 格式化的表格数据
   */
  const fetchData = async (params: Record<string, unknown>) => {
    try {
      // 处理分页参数
      const requestParams = {
        ...params,
        page: params.current,
        size: params.pageSize,
      };

      const res = await deviceProjectListApi(requestParams);

      if (res.success && res.data) {
        return {
          success: true,
          data: res.data.records ?? [],
          total: res.data.total ?? 0,
        };
      } else {
        window.$message.error(res.message || '获取项目列表失败');
        return {
          success: false,
          data: [],
          total: 0,
        };
      }
    } catch (error) {
      console.error('获取项目列表失败:', error);
      window.$message.error('获取项目列表失败，请稍后重试');
      return {
        success: false,
        data: [],
        total: 0,
      };
    }
  };

  /**
   * 删除单个项目
   * @param record 项目记录
   */
  const handleDelete = async (record: ProjectInfo) => {
    // 参数验证
    if (!record || !record.id) {
      window.$message.error('删除失败：项目ID不存在');
      return;
    }

    const projectName = record.name || '未知项目';

    AModal.confirm({
      title: '确认删除',
      content: `确定要删除项目"${projectName}"吗？删除后不可恢复。`,
      okText: '确定',
      cancelText: '取消',
      okType: 'danger',
      onOk: async () => {
        try {
          const res = await deviceProjectDeleteApi({ id: String(record.id) });
          if (res.success) {
            window.$message.success('项目删除成功');
            actionRef.current?.reload();
          } else {
            window.$message.error(res.message || '删除失败');
          }
        } catch (error) {
          console.error('删除项目失败:', error);
          window.$message.error('删除失败，请重试');
        }
      },
    });
  };

  /**
   * 打开新增项目抽屉
   */
  const handleAdd = () => {
    setDrawerType('ADD');
    setCurrentRecord({});
    form.resetFields();
    setDrawerShow(true);
  };

  /**
   * 打开编辑项目抽屉
   * @param record 项目记录
   */
  const handleEdit = async (record: ProjectInfo) => {
    if (!record || !record.id) {
      window.$message.error('项目ID不存在，无法编辑');
      return;
    }

    try {
      // 获取项目详情，包括设备信息
      const res = await deviceProjectDetailApi({ id: record.id });
      if (res.success && res.data) {
        setDrawerType('EDIT');
        // 使用包含设备信息的详情数据
        setCurrentRecord(res.data as ProjectDetail);
        setDrawerShow(true);

        // 延迟预填充表单数据
        setTimeout(() => {
          const data = res.data;
          const deviceIds = data.deviceIds ? data.deviceIds.split(',') : [];

          form.setFieldsValue({
            name: data.name || '',
            address: data.address || '',
            remark: data.remark || '',
            authorizationCode: data.authorizationCode || '',
            deviceIds: deviceIds,
          });
        }, 100);
      } else {
        window.$message.error('获取项目详情失败');
      }
    } catch (error) {
      console.error('获取项目详情失败:', error);
      window.$message.error('获取项目详情失败');
    }
  };

  /**
   * 保存项目
   * 支持新增和编辑两种模式
   */
  const handleSubmit = async () => {
    try {
      const values = await form.validateFields();

      // 处理设备ID，确保正确格式传递给后端
      const requestParams = {
        ...currentRecord,
        ...values,
      };

      // 如果有设备绑定，需要特殊处理deviceIds
      if (values.deviceIds) {
        // 确保deviceIds是逗号分隔的字符串格式
        if (Array.isArray(values.deviceIds)) {
          requestParams.deviceIds = values.deviceIds.join(',');
        }
      }

      const res = await deviceProjectAddApi(requestParams);
      if (res.success) {
        const successMessage = drawerType === 'ADD' ? '项目创建成功' : '项目更新成功';
        window.$message.success(successMessage);

        // 延迟关闭抽屉，确保用户看到成功提示
        setTimeout(() => {
          form.resetFields();
          handleDrawerClose();
          actionRef.current?.reload();
        }, 300);
      } else {
        window.$message.error(res.message || '保存失败');
      }
    } catch (error) {
      console.error('保存项目失败:', error);
      if (error instanceof Error) {
        window.$message.error(`保存失败：${error.message}`);
      } else {
        window.$message.error('保存失败，请重试');
      }
    }
  };

  /**
   * 关闭抽屉并重置状态
   */
  const handleDrawerClose = () => {
    setCurrentRecord({});
    setDrawerType('ADD');
    setDrawerShow(false);
    form.resetFields();
  };

  /**
   * 表格列配置
   */
  const columns: ProColumns<ProjectInfo>[] = [
    {
      title: '项目名称',
      dataIndex: 'name',
      key: 'name',
      ellipsis: true,
      search: true,
    },
    {
      title: '地址',
      dataIndex: 'address',
      key: 'address',
      ellipsis: true,
      search: true,
    },
    {
      title: '授权码',
      dataIndex: 'authorizationCode',
      key: 'authorizationCode',
      ellipsis: true,
      width: 220,
      search: false,
      copyable: true,
    },
    {
      title: '设备数量',
      dataIndex: 'deviceIds',
      key: 'deviceCount',
      width: 120,
      search: false,
      render: (_, record) => {
        if (record.deviceIds) {
          // 如果deviceIds是字符串，按逗号分割计算数量
          if (typeof record.deviceIds === 'string') {
            const deviceCount = record.deviceIds.split(',').filter(id => id.trim() !== '').length;
            return `${deviceCount} 台`;
          }
          // 如果deviceIds是数组，直接返回长度
          if (Array.isArray(record.deviceIds)) {
            return `${record.deviceIds.length} 台`;
          }
        }
        return '0 台';
      },
    },
    {
      title: '备注',
      dataIndex: 'remark',
      key: 'remark',
      width: 200,
      ellipsis: true,
      search: false,
      render: (_, record) => record.remark || <span style={{ color: '#999' }}>暂无备注</span>,
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      key: 'createTime',
      width: 180,
      search: false,
    },
    {
      title: '操作',
      key: 'action',
      width: 180,
      fixed: 'right',
      search: false,
      render: (_, record) => (
        <ASpace size="small">
          <AButton
            type="link"
            size="small"
            onClick={() => navigate(`/project/manager/detail/${record.id}`)}
          >
            详情
          </AButton>
          <AButton type="link" size="small" onClick={() => handleEdit(record)}>
            编辑
          </AButton>
          <AButton type="link" size="small" danger onClick={() => handleDelete(record)}>
            删除
          </AButton>
        </ASpace>
      ),
    },
  ];

  return (
    <div className="page-wrapper">
      <ADrawer
        destroyOnHidden
        title={`项目${OperationTypeList[drawerType].label}`}
        width={600}
        closable={{ 'aria-label': 'Close Button' }}
        footer={
          <ARow justify="end">
            <ASpace>
              <AButton
                onClick={() => {
                  setDrawerShow(false);
                }}
              >
                返回
              </AButton>
              {drawerType != 'DETAIL' && (
                <AButton type="primary" onClick={handleSubmit}>
                  提交
                </AButton>
              )}
            </ASpace>
          </ARow>
        }
        onClose={handleDrawerClose}
        open={drawerShow}
      >
        <div className="w-full px-8 py-8">
          <AForm form={form} layout="vertical" labelAlign="right" labelCol={{ span: 12 }}>
            <React.Suspense fallback={<ASpin />}>
              <ProjectAddForm
                form={form}
                data={currentRecord as ProjectInfo}
                mode={drawerType === 'EDIT' ? 'edit' : 'add'}
              />
            </React.Suspense>
          </AForm>
        </div>
      </ADrawer>

      <div className="page-title">
        <div className="page-main-title">项目管理</div>
        <div className="page-sub-title">项目管理提供了对项目的创建、编辑、删除等功能。</div>
      </div>

      <div className="page-content-box">
        <div className="page-content flex show-bg">
          <div className="w-full">
            <PProTable<ProjectInfo>
              className="mh-table"
              actionRef={actionRef}
              columns={columns}
              request={fetchData}
              rowKey="id"
              search={{
                span: 6,
                labelWidth: 'auto',
                defaultCollapsed: false,
              }}
              pagination={{
                defaultPageSize: 10,
                showSizeChanger: true,
                showQuickJumper: true,
                showTotal: (total, range) =>
                  `共 ${total} 项数据，当前显示第 ${range[0]}-${range[1]} 项`,
              }}
              scroll={{ x: 1000 }}
              size="small"
              options={{
                density: false,
                reloadIcon: (
                  <AButton icon={<ReloadOutlined />} key="reload">
                    刷新
                  </AButton>
                ),
                setting: {
                  draggable: true,
                  checkable: true,
                  showListItemOption: true,
                  settingIcon: <AButton icon={<SettingOutlined />}>设置</AButton>,
                  listsHeight: 400,
                },
              }}
              toolBarRender={() => [
                <AButton key="add" icon={<PlusOutlined />} type="primary" onClick={handleAdd}>
                  新增项目
                </AButton>,
              ]}
              locale={TableLocalePresets.product(actionRef)}
              tableAlertRender={false} // 隐藏"已选择 X 项"提示
              tableAlertOptionRender={false} // 隐藏"取消选择"等操作按钮
              rowSelection={false} // 移除行选择功能
            />
          </div>
        </div>
      </div>
    </div>
  );
};

export default ProjectManager;
